package com.ggb.reactive.security

import com.ggb.reactive.extension.thisLogger
import com.ggb.reactive.service.JwtSigner
import lombok.AllArgsConstructor
import org.springframework.security.authentication.ReactiveAuthenticationManager
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.Authentication
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.stereotype.Component
import reactor.core.publisher.Mono
import java.util.Collections
import java.util.stream.Stream
import kotlin.reflect.jvm.internal.impl.utils.CollectionsKt

@Component
@AllArgsConstructor
class JwtAuthenticationManager(val jwtSigner: JwtSigner): ReactiveAuthenticationManager {
    private val log = thisLogger()
    override fun authenticate(authentication: Authentication): Mono<Authentication> {
        println("访问 ReactiveAuthenticationManager  。。。。。。。。。。。")

        return Mono.just(authentication)
            .map {auth -> jwtSigner.parseToken(auth.credentials.toString()) }
            .log()
            .onErrorResume { e->
                log.error("验证token时发生错误，错误类型为：{},错误信息为：{}",e.javaClass,e.message)
                Mono.empty();
            }
            .map { claims->

                UsernamePasswordAuthenticationToken(
                    claims.subject,
                    null,
                    //这里的stream大可不必，就流动了一个元素
//                    Stream.of(claims.get(jwtSigner.authoritiesTag).toString())
//                        .peek { println("权限为： $it") }
//                        .map { authority -> SimpleGrantedAuthority(authority) }
//                        .toList()
                    run {
                        val rules = claims.get(jwtSigner.authoritiesTag).toString()
                        log.info("权限为:{}",rules)
                        val simpleGrantedAuthority = SimpleGrantedAuthority(rules)
                        listOf(simpleGrantedAuthority)
                    }
                )
            }

    }
}